package com.security.config;

import com.security.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @ClassName: SecurityAdapter
 * @Author: ZhangYue26
 * @Description: WebSecurityConfigurerAdapter配置了如何验证用户信息，新建该类用来配置HttpSecurity
 * @Date: 2021-01-19
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//prePostEnabled为true表示是否开启方法级别保护
//即@PreAuthorize与@PostAuthorize是否可用
public class SecurityAdapter extends WebSecurityConfigurerAdapter {

    /**
      * @Description 需要重写WebSecurityConfigurerAdapter中configure方法来配置HttpSecurity
      * @author ZhangYue26
      * @date 2021/1/19
      * @param [http]
      * @return void
      **/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                /** 配置index界面与css界面允许所有人访问，注意后面的permitAll()方法，允许任何人访问 */
                .antMatchers(Constants.Path.CSS.getPath(),Constants.Path.INDEX.getPath()).permitAll()
                /** 配置用户界面需要用户角色才能访问 */
                .antMatchers(Constants.Path.USER.getPath()).hasRole(Constants.Role.USER.getRole())
                /** 配置日志界面需要用户角色访问 */
                .antMatchers(Constants.Path.BLOGS.getPath()).hasRole(Constants.Role.USER.getRole())
                .and()
                /** 配置表单登录地址是登录界面，配置失败页面为错误界面 */
                .formLogin().loginPage(Constants.Path.LOGIN.getPath()).failureUrl(Constants.Path.ERROR.getPath())
                .and()
                /** 设置异常时重定向至异常界面 */
                .exceptionHandling().accessDeniedPage(Constants.Path.EXCEPTION.getPath());
        /** 指定成功退出页面为首页 */
        http.logout().logoutSuccessUrl("/");
    }

    /**
     * @Description 在内存中创建了一个用户并赋值密码与角色
     * @author ZhangYue26
     * @date 2021/1/19
     * @param [auth]
     * @return void
     **/
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password("123456").roles("USER");
    }

}
